package com.pfdu.simplescheduler.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Ticker;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Configuration
@Data
@ConfigurationProperties(prefix = "simple-scheduler")
public class CacheConfig {

    @Data
    public static class Config {
        private int duration; // 有效时长，单位秒
        private int size = 8; // 缓存池容量
    }

    private Map<String, Config> cache;

    @Bean
    public Ticker ticker() {
        return Ticker.systemTicker();
    }

    @Bean
    public CacheManager cacheManager(Ticker ticker) {
        List<CaffeineCache> caffeineCacheList = null;
        if (cache != null)
            caffeineCacheList = cache.entrySet()
                    .stream()
                    .map(entry -> buildCache(entry.getKey(), entry.getValue().duration, entry.getValue().size))
                    .collect(Collectors.toList());
        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        simpleCacheManager.setCaches(caffeineCacheList);
        return simpleCacheManager;
    }

    private CaffeineCache buildCache(String name, long duration, long size) {
        Cache<Object, Object> caffeine = Caffeine.newBuilder()
                .expireAfterWrite(duration, TimeUnit.SECONDS)
                .maximumSize(size)
                .ticker(ticker())
                .build();
        return new CaffeineCache(name, caffeine);
    }
}